package com.hyj.ecp.clientservice.goods.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ecp.cust.CustAddressee;
import com.ecp.goods.CustGoods;
import com.ecp.goods.GoodsQO;
import com.ecp.goods.GoodsTypeQO;
import com.hyj.ecp.clientservice.goods.service.IGoodsService;
import com.hyj.ecp.common.constant.SysConstant;
import com.hyj.util.GzipUtil;
import com.hyj.util.HttpUtil;
import com.hyj.util.JsonUtil;

@Controller
@RequestMapping("/client/goods/*")
public class GoodsAction {

	Log logger = LogFactory.getLog(GoodsAction.class);
	@Autowired
    private IGoodsService service;
	
	    @RequestMapping(value="goodstype.do", method=RequestMethod.POST)
	    public void goodstype(HttpServletRequest request,HttpServletResponse response) throws IOException
	    {
			logger.info("goodstype.do start...");
			//String userNum=request.getHeader("userNum");
			BufferedReader read = request.getReader();
			String ss = null;
			StringBuffer sbf  = new StringBuffer();
			while ((ss = read.readLine()) != null) {
				 sbf.append(ss);
			}
			String reqparam = sbf.toString();
			logger.info("请求参数" + reqparam);
			Map<String, Object>  map  = new HashMap<String,Object>();
			try{
				Map<?,?> m = (Map<?,?>) JsonUtil.fromJson(reqparam, Map.class);
				String account  = (String) m.get("Account");
				String password  = (String) m.get("Password");
				
				GoodsTypeQO qo = new GoodsTypeQO();
			    qo.setPid("-1");
				
			    List<GoodsTypeQO>  list = service.queryGoodsType(qo);
				map.put("ReturnCode", 0);
				map.put("List", list);
			}catch(Exception e){
				logger.error("goodstype.do 出错",e);
				map.put("ReturnCode", 999);
				map.put("List",new Object[]{});
			}
			 
			String json = JsonUtil.toJson(map, false);
			
			logger.info("返回参数：" + json);
			OutputStream out = null;
			String encoding = request.getHeader("Accept-Encoding");
			if (encoding != null && encoding.indexOf("gzip") != -1) {
				response.setHeader("Content-Encoding", "gzip");
				out = GzipUtil.getGzipOutputStream(response.getOutputStream());
			} else {
				out = response.getOutputStream();
			}
			out.write(json.getBytes("UTF-8"));
			out.flush();
			out.close();
			logger.info("goodstype.do end");
	    	
	    }
	    
	    /**
	     * 商品查询 返回列表
	     * @param request
	     * @param response
	     * @throws IOException
	     */
	    @RequestMapping(value="queryGoods.do", method=RequestMethod.POST)
	    public void queryGoods(HttpServletRequest request,HttpServletResponse response) throws IOException
	    {
			logger.info("queryGoods.do start...");
			//String userNum=request.getHeader("userNum");
			BufferedReader read = request.getReader();
			String ss = null;
			StringBuffer sbf  = new StringBuffer();
			while ((ss = read.readLine()) != null) {
				 sbf.append(ss);
			}
			String reqparam = sbf.toString();
			logger.info("请求参数" + reqparam);
			Map<String, Object>  map  = new HashMap<String,Object>();
			try{
				Map<?,?> m = (Map<?,?>) JsonUtil.fromJson(reqparam, Map.class);
				String account  = (String) m.get("Account");
				String password  = (String) m.get("Password");
				Integer typeId = JsonUtil.getParam("TypeId", m, Integer.class);
				String searKey  = (String) m.get("SearKey");
				String isHot  = (String) m.get("IsHot");
				String isAd  = (String) m.get("IsAd");
				Integer id = JsonUtil.getParam("Id", m, Integer.class);
				
				String orderBy  = JsonUtil.getParam("OrderBy", m, String.class);
				
				Integer pointPrice  = JsonUtil.getParam("PointPrice", m, Integer.class);
				pointPrice = pointPrice==null ? -1 : pointPrice;
				
				GoodsQO qo = new GoodsQO();
			    qo.setTypeId(typeId ==null ? 0 : typeId);
			    qo.setId(id==null ? 0 : id);
				qo.setName(searKey);
				qo.setIsHot(isHot);
				qo.setIsAd(isAd);
				qo.setOrderBy(orderBy);
				qo.setPointPrice(pointPrice);
				
				//图片服务器
				qo.setImgServer(SysConstant.getPropertiy("imageServer"));
				
			    List<Map<String,Object>>  list = service.queryGoods(qo);
				map.put("ReturnCode", 0);
				map.put("List", list);
			}catch(Exception e){
				logger.error("queryGoods.do 出错",e);
				map.put("ReturnCode", 999);
				map.put("List",new Object[]{});
			}
			 
			String json = JsonUtil.toJson(map, false);
			
			logger.info("返回参数：" + json);
			OutputStream out = null;
			String encoding = request.getHeader("Accept-Encoding");
			if (encoding != null && encoding.indexOf("gzip") != -1) {
				response.setHeader("Content-Encoding", "gzip");
				out = GzipUtil.getGzipOutputStream(response.getOutputStream());
			} else {
				out = response.getOutputStream();
			}
			out.write(json.getBytes("UTF-8"));
			out.flush();
			out.close();
			logger.info("queryGoods.do end");
	    	
	    }
	    
	    /**
	     * 查看商品的详细信息
	     * @param request
	     * @param response
	     * @throws IOException
	     */
	    @RequestMapping(value="queryGoodsInfo.do", method=RequestMethod.POST)
	    public void queryGoodsInfo(HttpServletRequest request,HttpServletResponse response) throws IOException
	    {
			logger.info("queryGoods.do start...");
			//String userNum=request.getHeader("userNum");
			BufferedReader read = request.getReader();
			String ss = null;
			StringBuffer sbf  = new StringBuffer();
			while ((ss = read.readLine()) != null) {
				 sbf.append(ss);
			}
			String reqparam = sbf.toString();
			logger.info("请求参数" + reqparam);
			Map<String, Object>  map  = new HashMap<String,Object>();
			try{
				Map<?,?> m = (Map<?,?>) JsonUtil.fromJson(reqparam, Map.class);
				String account  = (String) m.get("Account");
				String password  = (String) m.get("Password");
				Integer id = JsonUtil.getParam("GoodsId", m, Integer.class);
				
				
				GoodsQO qo = new GoodsQO();
				qo.setId(id==null ? 0 :id);
				
				//图片服务器
				qo.setImgServer(SysConstant.getPropertiy("imageServer"));
				
			    Map<String,Object>  obj = service.queryGoodsInfo(qo);
			    
			    // XG  商品详情图片添加前缀
			    //商品详情HTML图片前缀添加
			    String html = (String) obj.get("DESC");
			    Document  doc = Jsoup.parse(html);
			    Elements imgs =  doc.getElementsByTag("img");
				for (Element img : imgs) {
					String src = img.attr("src");
					if (!src.startsWith("http://")) {
						src = SysConstant.getPropertiy("imageServer") + src;
						img.attr("src", src);
					}
				}
			    map.put("DESC", doc.html());
			    
				map.put("ReturnCode", 0);
				map.put("info", obj);
			}catch(Exception e){
				logger.error("queryGoods.do 出错",e);
				map.put("ReturnCode", 999);
				map.put("List",new Object[]{});
			}
			 
			String json = JsonUtil.toJson(map, false);
			
			logger.info("返回参数：" + json);
			OutputStream out = null;
			String encoding = request.getHeader("Accept-Encoding");
			if (encoding != null && encoding.indexOf("gzip") != -1) {
				response.setHeader("Content-Encoding", "gzip");
				out = GzipUtil.getGzipOutputStream(response.getOutputStream());
			} else {
				out = response.getOutputStream();
			}
			out.write(json.getBytes("UTF-8"));
			out.flush();
			out.close();
			logger.info("queryGoods.do end");
	    	
	    }
	    
	    //收藏接口
	    @RequestMapping(value="saveCustgoods.do", method=RequestMethod.POST)
	    public void storegoods(HttpServletRequest request,HttpServletResponse response) throws IOException
	    {
			logger.info("saveCustgoods.do start...");
			BufferedReader read = request.getReader();
			String ss = null;
			StringBuffer sbf  = new StringBuffer();
			while ((ss = read.readLine()) != null) {
				 sbf.append(ss);
			}
			String reqparam = sbf.toString();
			logger.info("请求参数" + reqparam);
			Map<String, Object>  map  = new HashMap<String,Object>();
			try{
				Map<?,?> m = (Map<?,?>) JsonUtil.fromJson(reqparam, Map.class);
				String account  = (String) m.get("Account");
				String password  = (String) m.get("Password");
				Integer goodsid  = JsonUtil.getParam("GoodsId", m, Integer.class);
				
				CustGoods qo = new CustGoods();
			    qo.setGoogsid(goodsid!=null ? goodsid : 0);
			    qo.setAccount(account);
			    int  num = service.saveCustGoods(qo);
			    if(num >0){
					map.put("ReturnCode", 0);
					map.put("msg", SysConstant.SAVE_SUCCESS_STR);
			    }else{
			    	map.put("ReturnCode", 999);
					map.put("msg", SysConstant.SAVE_FAIL_STR);
			    }
			}catch(Exception e){
				logger.error("goodstype.do 出错",e);
				map.put("ReturnCode", 999);
				map.put("msg", SysConstant.SAVE_FAIL_STR);
			}
			 
			String json = JsonUtil.toJson(map, false);
			
			logger.info("返回参数：" + json);
			OutputStream out = null;
			String encoding = request.getHeader("Accept-Encoding");
			if (encoding != null && encoding.indexOf("gzip") != -1) {
				response.setHeader("Content-Encoding", "gzip");
				out = GzipUtil.getGzipOutputStream(response.getOutputStream());
			} else {
				out = response.getOutputStream();
			}
			out.write(json.getBytes("UTF-8"));
			out.flush();
			out.close();
			logger.info("saveCustgoods.do end");
	    	
	    }
	    
	    
	     //收藏接口
	    @RequestMapping(value="queryCustgoods.do", method=RequestMethod.POST)
	    public void queryCustgoods(HttpServletRequest request,HttpServletResponse response) throws IOException
	    {
			logger.info("queryCustgoods.do start...");
			Map<String, Object>  map  = new HashMap<String,Object>();
			try{
				Map<?,?> m = HttpUtil.ParserRequest(request);
				String account  = (String) m.get("Account");
				String password  = (String) m.get("Password");
				
				CustGoods qo = new CustGoods();
			    qo.setAccount(account);
			    List<Map<String,Object>>  list = service.queryCustGoods(qo);
			     
				map.put("ReturnCode", 0);
				map.put("list", list);
			    
			}catch(Exception e){
				logger.error("queryCustgoods.do 出错",e);
				map.put("ReturnCode", 999);
				map.put("List",new Object[]{});
			}
			 
			String json = JsonUtil.toJson(map, false);
			
			logger.info("返回参数：" + json);
			OutputStream out = HttpUtil.writeResponse(request, response);
			out.write(json.getBytes("UTF-8"));
			out.flush();
			out.close();
			logger.info("queryCustgoods.do end");
	    	
	    }
	    
	    
	    /**
	     * 删除 收藏
	     * @param request
	     * @param response
	     * @throws UnsupportedEncodingException
	     * @throws IOException
	     */
	    @RequestMapping(value = "deleteCustgoods.do", method = RequestMethod.POST)
		public void deleteCustgoods(HttpServletRequest request,HttpServletResponse response 
				) throws UnsupportedEncodingException, IOException {
			logger.info("deleteCustgoods.do start...");
			 
			Map<String, Object>  map  = new HashMap<String,Object>();
			try{
				Map<?,?> m = HttpUtil.ParserRequest(request);
				String account  = (String) m.get("Account");
				String password  = (String) m.get("Password");
				Integer id  = JsonUtil.getParam("Id", m, Integer.class);
				CustGoods qo = new CustGoods();
			    qo.setAccount(account);
			    qo.setId(id);
	            
			    int a = service.deleteCustGoods(qo);
			    map.put("ReturnCode", 0);
			    map.put("msg", "删除收藏成功！");
			}catch(Exception e){
				logger.error("deleteCustgoods.do 出错",e);
				map.put("ReturnCode", 999);
			    map.put("msg", "删除收藏失败！");
			}
			 
			String json = JsonUtil.toJson(map, false);
			
			logger.info("返回参数：" + json);
			OutputStream out = HttpUtil.writeResponse(request, response);
			out.write(json.getBytes("UTF-8"));
			out.flush();
			out.close();
			logger.info("deleteCustgoods.do end");
			 
		}
	    
	    /**
	     * 商品贵就赔 等活动 信息返回
	     * @param request
	     * @param response
	     * @ActType 
	     * ActType : gjp  --贵就赔
           khfw --客户服务
           cjwt --常见问题
           jgbh  --价格保护
	     * @throws IOException
	     */
	    @RequestMapping(value = "goodsActInfo.do", method = RequestMethod.POST)
	    public void goodsActivityInfo(HttpServletRequest request,HttpServletResponse response  
	    		) throws UnsupportedEncodingException, IOException {
			logger.info("goodsActInfo.do start...");
			Map<String, Object>  map  = new HashMap<String,Object>();
			try{
				Map<?,?> m = HttpUtil.ParserRequest(request);
				String account  = (String) m.get("Account");
				String password  = (String) m.get("Password");
				String actType  = (String) m.get("ActType");
				CustGoods qo = new CustGoods();
			    qo.setAccount(account);
			    qo.setActivityType(actType);
			    
			    String info = service.goodsActivityInfo(qo);
			    
			    map.put("ReturnCode", 0);
			    map.put("info", info);
			}catch(Exception e){
				logger.error("goodsActInfo.do 出错",e);
				map.put("ReturnCode", 999);
			    map.put("info", e.getMessage());
			}
			 
			String json = JsonUtil.toJson(map, false);
			
			logger.info("返回参数：" + json);
			OutputStream out = HttpUtil.writeResponse(request, response);
			out.write(json.getBytes("UTF-8"));
			out.flush();
			out.close();
			logger.info("goodsActInfo.do end");
			 
		}
}
